﻿using LeSoft.Application.Bussiness;
using LeSoft.Application.Code;
using LeSoft.Application.Entity;
using LeSoft.Util;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LeSoft.Application.Web.Areas.ResourceManage.Controllers
{
    public class RS_ProductStockController : MvcControllerBase
    {
        private WarehouseBLL bll = new WarehouseBLL();

        #region 视图
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit, "库存查询首页", "Index")]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit, "", "Form")]
        public ActionResult Form()
        {
            return View();
        }
        #endregion

        #region 获取数据
        /// <summary>
        /// 获取仓库集合
        /// </summary>
        /// <param name="WarehouseType"></param>
        /// <param name="ProductType"></param>
        /// <returns></returns> 
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取仓库集合", "GetWarehouseData")]
        public ActionResult GetWarehouseData(string WarehouseType, string ProductType)
        {

            var data = bll.GetWarehouseInfoList().ToList();
            if (!WarehouseType.IsEmpty() && WarehouseType != "All")
            {
                data = data.Where(t => t.Id.Contains(WarehouseType)).ToList();
            }
            return Content(data.ToJson());
        }

        /// <summary>
        /// 获取仓库物品
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取仓库物品", "GetProductListByWarehouseId")]
        public ActionResult GetProductListByWarehouseId(string queryJson)
        {
            var queryParam = queryJson.ToJObject();
            var data = bll.GetWarehouseProductList().ToList();
            data = data.OrderByDescending(s => s.CreateDate).ToList();
            if (!queryParam["WarehouseId"].IsEmpty())
            {
                data = data.Where(e => e.WarehouseId == queryParam["WarehouseId"].ToString() && e.Num > 0).ToList();
            }
            if (!queryParam["ProductType"].IsEmpty())
            {
                data = data.Where(e => e.ProductId == queryParam["ProductType"].ToString()).ToList();
            }
            if (!queryParam["condition"].IsEmpty() && !queryParam["keyword"].IsEmpty())
            {
                var condition = queryParam["condition"].ToString();
                var keyword = queryParam["keyword"].ToString();
                switch (condition)
                {
                    case "Name":
                        data = data.Where(t => t.Name.Contains(keyword)).ToList();
                        break;
                    case "Code":
                        data = data.Where(t => t.Code.Contains(keyword)).ToList();
                        break;
                    default:
                        break;
                }
            }
            return Content(data.ToJson());

        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取仓库物品集合", "GetWarehouseProductList")]
        public ActionResult GetWarehouseProductList(string queryJson)
        {
            var queryParam = queryJson.ToJObject();
            var data = bll.GetWarehouseProductList().ToList();
            data = data.OrderByDescending(s => s.CreateDate).ToList();
            if (!queryParam["WarehouseType"].IsEmpty() && queryParam["WarehouseType"].ToString() != "All")
            {
                data = data.Where(e => e.WarehouseId == queryParam["WarehouseType"].ToString()).ToList();
            }
            if (!queryParam["ProductType"].IsEmpty() && queryParam["ProductType"].ToString() != "All")
            {
                data = data.Where(e => e.Type == queryParam["ProductType"].ToString()).ToList();
            }
            if (!queryParam["keyword"].IsEmpty())
            {
                var condition = !queryParam["condition"].IsEmpty() ? queryParam["condition"].ToString() : "";
                var keyword = queryParam["keyword"].ToString();
                switch (condition)
                {
                    case "Name":
                        data = data.Where(t => t.Name.Contains(keyword)).ToList();
                        break;
                    case "Code":
                        data = data.Where(t => t.Code.Contains(keyword)).ToList();
                        break;
                    case "Brand":
                        data = data.Where(t => t.Brand.Contains(keyword)).ToList();
                        break;
                    case "ModelNo":
                        data = data.Where(t => t.ModelNo.Contains(keyword)).ToList();
                        break;
                    default:
                        data = data.Where(t => t.Code.Contains(keyword) || t.Name.Contains(keyword) || t.Brand.Contains(keyword) || t.ModelNo.Contains(keyword)).ToList();
                        break;
                }
            }
            foreach (var item in data)
            {
                var query = bll.GetProductTypeList().Where(e => e.Id == item.Type).FirstOrDefault();
                if (query == null)
                {
                    item.Type = "---";
                }
                else
                {
                    item.Type = query.Name;
                }
            }
            List<WarehouseProductEntity> WpLst = new List<WarehouseProductEntity>();
            foreach (var item in data)
            {
                if (WpLst.Count(e => e.ProductId == item.ProductId) == 0)
                {
                    WpLst.Add(item);
                }
            }
            data = WpLst.ToList();
            if (!queryParam["WarehouseType"].IsEmpty() && queryParam["WarehouseType"].ToString() != "All")
            {
                data = data.Where(e => e.WarehouseId == queryParam["WarehouseType"].ToString()).ToList();
                string str = "[";
                foreach (var item in data)
                {
                    var Wentity = bll.GetWarehouseInfoEntity(queryParam["WarehouseType"].ToString());
                    str += "{\"Id\":\"" + item.ProductId + "\",";
                    str += "\"Type\":\"" + item.Type + "\",\"Code\":\"" + item.Code + "\",\"Name\":\"" + item.Name + "\",\"ModelNo\":\"" + item.ModelNo + "\",\"Brand\":\"" + item.Brand + "\",\"Unit\":\"" + item.Unit + "\",\"Volume\":\"" + item.Num + "\",";
                    str += "\"Num" + Wentity.Code + "\":\"" + item.Num + "\",\"AverageUnitPrice" + Wentity.Code + "\":\"" + item.AverageUnitPrice + "\",\"TaxUnitPrice" + Wentity.Code + "\":\"" + item.TaxUnitPrice + "\",\"UnitPrice" + Wentity.Code + "\":\"" + item.UnitPrice + "\",\"Price" + Wentity.Code + "\":\"" + item.Price + "\",";
                    var s = item.Description.IsEmpty() ? " " : item.Description;
                    str += "\"Description\":\"" + s + "\"},";
                }
                str += "]";
                str = str.Replace(",]", "]");
                object obj = JsonConvert.DeserializeObject<object>(str);
                return Content(obj.ToJson());
            }
            else
            {
                string str = "[";
                foreach (var item in data)
                {
                    int Count = 0;
                    var c = bll.GetWarehouseProductList().Where(e => e.ProductId == item.ProductId).ToList();
                    if (c.Count() > 0)
                    {
                        foreach (var cc in c)
                        {
                            Count += cc.Num.ToInt();
                        }
                    }
                    var Wlst = bll.GetWarehouseInfoList();
                    str += "{\"Id\":\"" + item.ProductId + "\",";
                    str += "\"Type\":\"" + item.Type + "\",\"Code\":\"" + item.Code + "\",\"Name\":\"" + item.Name + "\",\"ModelNo\":\"" + item.ModelNo + "\",\"Brand\":\"" + item.Brand + "\",\"Unit\":\"" + item.Unit + "\",\"Volume\":\"" + Count + "\",";
                    foreach (var a in Wlst)
                    {
                        var b = bll.GetWarehouseProductList().FirstOrDefault(e => e.WarehouseId == a.Id && e.ProductId == item.ProductId);
                        if (!b.IsEmpty())
                        {
                            str += "\"Num" + a.Code + "\":\"" + b.Num + "\",\"AverageUnitPrice" + a.Code + "\":\"" + b.AverageUnitPrice + "\",\"TaxUnitPrice" + a.Code + "\":\"" + b.TaxUnitPrice + "\",\"UnitPrice" + a.Code + "\":\"" + b.UnitPrice + "\",\"Price" + a.Code + "\":\"" + b.Price + "\",";

                        }

                    }
                    var s = item.Description.IsEmpty() ? "" : item.Description;
                    str += "\"Description\":\"" + s + "\"},";
                }
                str += "]";
                str = str.Replace(",]", "]");
                object obj = JsonConvert.DeserializeObject<object>(str);
                return Content(obj.ToJson());
            }

        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "仓库物品", "GetWarehouseProductFormJson")]
        public ActionResult GetWarehouseProductFormJson(string keyValue)
        {
            var data = bll.GetWarehouseProductEntity(keyValue);
            return Content(data.ToJson());
        }
        #endregion

        #region 保存数据
        /// <summary>
        /// 保存仓库物品
        /// </summary>
        /// <param name="keyValue"></param>
        /// <param name="entity"></param>
        /// <returns></returns> 
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "保存仓库物品", "SaveWarehouseProducForm")]
        public ActionResult SaveWarehouseProducForm(string keyValue, WarehouseProductEntity entity)
        {
            var type = entity.Type;
            if (type == "All")
            {
                return Error("所有物品不能作为物品类型使用！");
            }
            try
            {
                bll.SaveWarehouseProducForm(keyValue, entity);
                return Success("操作成功。");

            }
            catch (Exception e)
            {
                return Error("操作失败：" + e.Message);
            }

        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "删除仓库物品", "RemoveWarehouseProductForm")]
        public ActionResult RemoveWarehouseProductForm(string keyValue)
        {
            try
            {
                bll.RemoveWarehouseProducForm(keyValue);
                return Success("删除成功。");
            }
            catch (Exception e)
            {
                return Error("操作失败：" + e.Message);
            }

        }
        #endregion






    }
}
